package net.njcp.spi.selector;

import net.njcp.spi.exception.NoSpiMatchException;
import net.njcp.spi.selector.api.ISelector;
import net.njcp.spi.selector.api.SpiImplWrapper;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * @ClassName DefaultSelector
 * @Description: 对每个实现类赋予唯一的name，默认选择器则表示根据name来查找实现类
 * @Author 柳拓
 * @Date 2019/8/6
 * @Version V1.0
 **/
public class DefaultSelector implements ISelector<String> {


    @Override
    public <K> K selector(Map<String, SpiImplWrapper<K>> map, String name) throws NoSpiMatchException {
        /*if (StringUtils.isBlank(name)) {
            throw new IllegalArgumentException("spiName should not be empty!");
        }*/

        if (map == null || map.size() == 0) {
            throw new IllegalArgumentException("no impl spi!");
        }

        if(name != null){
            if (!map.containsKey(name)) {
                throw new NoSpiMatchException("no spiImpl match the name you choose! your choose is: " + name);
            }

            return map.get(name).getSpiImpl();
        }else {

            return map.entrySet().iterator().next().getValue().getSpiImpl();
        }
    }

}